package com.gm.wholesale.module.login.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;

import androidx.annotation.Nullable;

import com.gm.commonlib.base.baseBean.DataResp;
import com.gm.commonlib.network.BaseHttpObserver;
import com.gm.commonlib.views.dialog.DialogUtil;
import com.gm.commonlib.views.dialog.loadingDialog.LoadingDialog;
import com.gm.commonlib.views.toast.ToastUtil;
import com.gm.wholesale.cacheData.CacheData;
import com.gm.wholesale.constant.WebPath;
import com.gm.wholesale.module.config.ConfigData;
import com.gm.wholesale.module.config.bean.ConfigBean;
import com.gm.wholesale.module.config.model.ConfigModel;
import com.gm.wholesale.module.login.jsfunction.LoginWebViewCallBack;
import com.gm.wholesale.module.main.ui.MainActivity;
import com.gm.wholesale.module.user.UserDataManger;
import com.gm.wholesale.module.webview.MyBaseWebView;

public class LoginActivity extends MyBaseWebView {


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        UserDataManger.newInstance().clear();
        mViewView.clearCache(true);
        loadUrl(WebPath.LOGIN);
        bindCallBackMethod();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (MainActivity.mActivity!=null){ //防止没有 finish
            MainActivity.mActivity.finish();
            MainActivity.mActivity=null;
            System.gc();

        }
    }

    // todo 绑定js回调的类
    private void bindCallBackMethod() {
        mViewView.addJavascriptInterface(new LoginWebViewCallBack(this), LoginWebViewCallBack.loginViewCallBack);
    }

    //todo 跳转到主界面
    public void startMainActivity() {
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }

    public void loginSuccess() {
        getConfig();
    }

    private void getConfig(){
        LoadingDialog.newLoadingDialog().show(getActivity());
        ConfigModel.getConfig(null, new BaseHttpObserver<>() {
            @Override
            protected void handleResultOkResp(DataResp<ConfigBean> resp) {
                ConfigData.getConfigData().setConfigBean(resp.getData());
                startMainActivity();
            }

            @Override
            protected void onError(String error) {
                ToastUtil.showToast(error);
                startLoginAct();
                finish();
            }

            @Override
            public void onComplete() {
                LoadingDialog.newLoadingDialog().hid();
            }
        });
    }

    private void startLoginAct() {
        startActivity(new Intent(this, LoginActivity.class));
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        finish();
        return super.onKeyDown(keyCode, event);
    }
}
